package com.lmb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lmb.bean.Category;
import com.lmb.bean.R;
import com.lmb.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/category")
@RestController
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类    /category  +  post
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        categoryService.save(category);
        return R.success("新增成功");
    }

    /**
     * 分类分页查询
     * @param page
     * @param pageSize
     * @return
     */
    //1.MyBatisPlus分页查询拦截器已经配置
    //2.根据当前页码和每页显示条数 对category表进行分页查询
    @GetMapping("/page")
    public R<Page<Category>> page(@RequestParam(defaultValue="1") int page, @RequestParam(defaultValue="10") int pageSize){
        //1.调用service处理
        Page<Category> categoryPage = new Page<>(page, pageSize);

        //创建wrapper对象 设置排序字段
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);

        categoryService.page(categoryPage,wrapper);

        //2.响应处理结果
        return R.success(categoryPage);
    }

    //分类删除 优化后
    @DeleteMapping("/{id}")
    public R<String> delete(@PathVariable Long id){
        //1.调用service处理
        categoryService.deleteById(id);

        //2.响应处理结果
        return R.success("删除成功！");
    }

    //分类修改
    @PutMapping
    public R<String> update(@RequestBody Category category){
        //1.调用service处理
        categoryService.updateCategory(category);

        //2.响应处理结果
        return R.success("修改成功！");
    }

    //根据类型type查询指定菜品分类或套餐分类数据
    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(type!=null,Category::getType,type);

        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }

}
